package com.older.wptsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.older.wptsb.domain.dto.ElderDTO;
import com.older.wptsb.domain.po.Community;
import com.older.wptsb.domain.po.Elder;
import com.older.wptsb.domain.po.HealthData;
import com.older.wptsb.domain.po.User;
import com.older.wptsb.domain.vo.ElderVO;
import com.older.wptsb.domain.vo.HealthDataVO;
import com.older.wptsb.exception.CommunityException;
import com.older.wptsb.mapper.*;
import com.older.wptsb.service.CommunityElderService;
import com.older.wptsb.util.Result;
import com.older.wptsb.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommunityElderServiceImpl extends ServiceImpl<CommunityElderMapper, Elder> implements CommunityElderService {

    @Resource
    private CommunityElderMapper communityElderMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private HealthDataMapper healthDataMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private CommunityMapper communityMapper;
    @Resource
    private ElderMapper elderMapper;

    //查询社区老人列表
    @Override
    public List<ElderVO> getElderList() {
        Long currentUserId = UserContext.getUserId();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", currentUserId));
        List<Elder> elders = communityElderMapper.selectList(new QueryWrapper<Elder>().eq("community_id", user.getCommunityId()));
        return elders.stream().map(elder -> ElderVO.builder()
                .elderId(elder.getElderId())
                .name(elder.getName())
                .gender(elder.getGender())
                .age(elder.getAge())
                .idCard(elder.getIdCard())
                .communityId(elder.getCommunityId())
                .address(elder.getAddress())
                .healthSummary(elder.getHealthSummary())
                .emergencyContacts(elder.getEmergencyContacts())
                .emergencyPhone(elder.getEmergencyPhone())
                .status(elder.getStatus())
                .build()
        ).collect(Collectors.toList());
    }

    //添加老人
    @Override
    public void addElder(ElderDTO elderDTO) {
        Elder elder = communityElderMapper.selectOne(new QueryWrapper<Elder>().eq("name", elderDTO.getName()));
        if (elder == null) {
            LocalDateTime now = LocalDateTime.now();
            String formattedNow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            communityElderMapper.insert(Elder.builder()
                    .name(elderDTO.getName())
                    .gender(elderDTO.getGender())
                    .age(elderDTO.getAge())
                    .idCard(elderDTO.getIdCard())
                    .communityId(elderDTO.getCommunityId())
                    .address(elderDTO.getAddress())
                    .healthSummary(elderDTO.getHealthSummary())
                    .status(elderDTO.getStatus())
                    .emergencyContacts(elderDTO.getEmergencyContacts())
                    .emergencyPhone(elderDTO.getEmergencyPhone())
                    .createTime(formattedNow)
                    .build()
            );
            Community community = communityMapper.selectOne(new QueryWrapper<Community>().eq("community_id", elderDTO.getCommunityId()));
            communityMapper.update(Community.builder()
                    .elderCount(community.getElderCount() + 1)
                    .build(), new QueryWrapper<Community>().eq("community_id", elderDTO.getCommunityId())
            );
        } else {
            throw new CommunityException("添加失败");
        }

    }

    //修改老人信息
    @Override
    public void updateElder(ElderDTO elderDTO) {
        communityElderMapper.update(Elder.builder()
                .name(elderDTO.getName())
                .gender(elderDTO.getGender())
                .age(elderDTO.getAge())
                .idCard(elderDTO.getIdCard())
                .address(elderDTO.getAddress())
                .healthSummary(elderDTO.getHealthSummary())
                .status(elderDTO.getStatus())
                .emergencyContacts(elderDTO.getEmergencyContacts())
                .emergencyPhone(elderDTO.getEmergencyPhone())
                .build(), new QueryWrapper<Elder>().eq("elder_id", elderDTO.getElderId())
        );
    }

    @Override
    public ElderVO getElder(Integer id) {
        Elder elder = communityElderMapper.selectOne(new QueryWrapper<Elder>().eq("elder_id", id));
        return ElderVO.builder()
                .elderId(elder.getElderId())
                .name(elder.getName())
                .gender(elder.getGender())
                .age(elder.getAge())
                .idCard(elder.getIdCard())
                .communityId(elder.getCommunityId())
                .address(elder.getAddress())
                .healthSummary(elder.getHealthSummary())
                .status(elder.getStatus())
                .emergencyContacts(elder.getEmergencyContacts())
                .emergencyPhone(elder.getEmergencyPhone())
                .build();
    }

    @Override
    public List<HealthDataVO> getElderHealthData() {
        Long currentUserId = UserContext.getUserId();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_id", currentUserId));

        // 先从Redis中获取所有老人的健康数据
        List<HealthDataVO> healthDataList = new ArrayList<>();
        List<Elder> elders = communityElderMapper.selectList(new QueryWrapper<Elder>().eq("community_id", user.getCommunityId()));

        boolean hasRedisData = false;

        // 遍历所有老人，从Redis获取健康数据
        for (Elder elder : elders) {
            String redisKey = "health_data:" + elder.getElderId();
            List<Object> rawDataList = redisTemplate.opsForList().range(redisKey, 0, -1); // 获取所有数据，而不是只获取最新的一个数据

            // 如果Redis中有数据，则进行类型转换
            if (rawDataList != null && !rawDataList.isEmpty()) {
                hasRedisData = true;
                for (Object obj : rawDataList) {
                    if (obj instanceof HealthData) {
                        HealthData healthData = (HealthData) obj;
                        HealthDataVO vo = HealthDataVO.builder()
                                .dataId(healthData.getDataId())
                                .elderId(healthData.getElderId())
                                .communityId(healthData.getCommunityId())
                                .elderName(healthData.getElderName())
                                .heartRate(healthData.getHeartRate())
                                .bloodOxygen(healthData.getBloodOxygen())
                                .bloodPressure(healthData.getBloodPressure())
                                .sleepQuality(healthData.getSleepQuality())
                                .createTime(healthData.getCreateTime())
                                .location(healthData.getLocation())
                                .alertLevel(healthData.getAlertLevel())
                                .build();
                        healthDataList.add(vo);
                    }
                }
            }
        }

        // 如果Redis中有数据，则直接返回
        if (hasRedisData) {
            return healthDataList;
        }

        // 如果Redis中没有数据，则从数据库获取
        List<HealthData> healthData1 = healthDataMapper.selectList(new QueryWrapper<HealthData>().eq("community_id", user.getCommunityId()));
        return healthData1.stream().map(healthData -> HealthDataVO.builder()
                .dataId(healthData.getDataId())
                .elderId(healthData.getElderId())
                .communityId(healthData.getCommunityId())
                .elderName(healthData.getElderName())
                .heartRate(healthData.getHeartRate())
                .bloodOxygen(healthData.getBloodOxygen())
                .bloodPressure(healthData.getBloodPressure())
                .sleepQuality(healthData.getSleepQuality())
                .createTime(healthData.getCreateTime())
                .location(healthData.getLocation())
                .alertLevel(healthData.getAlertLevel())
                .build()
        ).collect(Collectors.toList());
    }


    @Override
    public List<HealthDataVO> getElderHealthDataById(Integer id) {
        // 从Redis获取健康数据
        String redisKey = "health_data:" + id;
        System.out.println(redisKey);
        List<Object> rawDataList = redisTemplate.opsForList().range(redisKey, 0, -1);
        System.out.println(rawDataList);
        List<HealthData> healthDataList = new ArrayList<>();

        // 如果Redis中有数据，则进行类型转换
        if (rawDataList != null && !rawDataList.isEmpty()) {
            for (Object obj : rawDataList) {
                if (obj instanceof HealthData) {
                    healthDataList.add((HealthData) obj);
                }
            }
        }
        // 如果Redis中没有有效数据，则从数据库获取
        if (healthDataList.isEmpty()) {
            // 查询数据库中该老人的所有健康数据，按时间倒序排列
            healthDataList = healthDataMapper.selectList(
                    new QueryWrapper<HealthData>()
                            .eq("elder_id", id)
                            .orderByDesc("create_time")
            );
        }
        // 转换为VO对象
        return healthDataList.stream().map(healthData -> HealthDataVO.builder()
                .dataId(healthData.getDataId())
                .elderId(healthData.getElderId())
                .communityId(healthData.getCommunityId())
                .elderName(healthData.getElderName())
                .heartRate(healthData.getHeartRate())
                .bloodOxygen(healthData.getBloodOxygen())
                .bloodPressure(healthData.getBloodPressure())
                .sleepQuality(healthData.getSleepQuality())
                .createTime(healthData.getCreateTime())
                .location(healthData.getLocation())
                .build()
        ).collect(Collectors.toList());
    }

    @Override
    public void deleterElder(Integer id) {

        Elder elder = communityElderMapper.selectOne(new QueryWrapper<Elder>().eq("elder_id", id));
        // 先获取要删除的老人信息
      if (elder != null && elder.getCommunityId() != null) {
    Integer communityId = Integer.valueOf(elder.getCommunityId());

    // 删除老人
    communityElderMapper.delete(new QueryWrapper<Elder>().eq("elder_id", id));

    // 重新统计并更新社区老人计数
    Integer count = communityElderMapper.selectCount(new QueryWrapper<Elder>().eq("community_id", communityId));
    communityMapper.updateElderCount(communityId, count);

        }
    }
}
